export const createStore = (reducer, initState) => {
  let state = initState;

  let listeners = [];

  const getState = () => state;

  const subscribe = (handler) => {
    // 订阅了这个数据的handler，在数据改变时，这个函数都能执行
    listeners.push(handler);
  };

  const dispatch = (action) => {
    const currentState = reducer(state, action);
    state = currentState;
    listeners.forEach((fn) => fn());
  };

  dispatch({type: Symbol()});

  return {
    getState,
    subscribe,
    dispatch,
  };
};

export const combineReduer = (reducers) => {
  const keys = Object.keys(reducers);

  return (state, action) => {
    const nextState = {};
    keys.forEach((key) => {
      const reducer = reducers[key];
      const prev = state[key];
      const next = reducer(prev, action);
      nextState[key] = next;
    });
    return nextState;
  };
};
